# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QSizePolicy,
    QSpacerItem,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import csv
import os
import json
import subprocess
import copy
from gui.controls import envs
from datetime import datetime
from .. import message_box as MBox
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModeResetCls
from ..custom_widget import LineEditFloat, LineEditStr, SelectBox


class DlgStringedBarEdit(DlgModeResetCls):
    ok_signal = Signal(str, list, int)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.widgetDict = {}
        self.type = params.get("type") or "add"
        self.row = params.get("row")
        self.data = params.get("data") or []
        self.names = params.get("names") or {}
        self.isPriorityDim = params.get("isPriorityDim") or False
        self.currentType = ""
        self.setWindowTitle("新增桁条" if self.type == "add" else "修改桁条")

        self.options = [
            {"value": "BAR", "title": "BAR", "num": 2},
            {"value": "BOX", "title": "BOX", "num": 4},
            {"value": "BOX1", "title": "BOX1", "num": 6},
            {"value": "CHAN", "title": "CHAN", "num": 4},
            {"value": "CHAN1", "title": "CHAN1", "num": 4},
            {"value": "CHAN2", "title": "CHAN2", "num": 4},
            {"value": "CROSS", "title": "CROSS", "num": 4},
            {"value": "DBOX", "title": "DBOX", "num": 10},
            {"value": "H", "title": "H", "num": 4},
            {"value": "HAT", "title": "HAT", "num": 4},
            {"value": "HAT1", "title": "HAT1", "num": 5},
            {"value": "HEXA", "title": "HEXA", "num": 3},
            {"value": "I", "title": "I", "num": 6},
            {"value": "l1", "title": "l1", "num": 4},
            {"value": "ROD", "title": "ROD", "num": 1},
            {"value": "T", "title": "T", "num": 4},
            {"value": "T1", "title": "T1", "num": 4},
            {"value": "T2", "title": "T2", "num": 4},
            {"value": "TUBE", "title": "TUBE", "num": 2},
            {"value": "TUBE2", "title": "TUBE2", "num": 2},
            {"value": "Z", "title": "Z", "num": 4},
        ]
        self.paramsList = [
            {"name": "name", "type": "str", "title": "名称"},
            {
                "name": "type",
                "type": "select",
                "title": "类型",
                "options": self.options,
                "onChanged": lambda value, *args, **kwargs: self.typeChange(
                    value, *args, **kwargs
                ),
            },
            {"name": "DIM1", "type": "float", "title": "DIM1"},
            {"name": "DIM2", "type": "float", "title": "DIM2"},
            {"name": "DIM3", "type": "float", "title": "DIM3"},
            {"name": "DIM4", "type": "float", "title": "DIM4"},
            {"name": "DIM5", "type": "float", "title": "DIM5"},
            {"name": "DIM6", "type": "float", "title": "DIM6"},
            {"name": "DIM7", "type": "float", "title": "DIM7"},
            {"name": "DIM8", "type": "float", "title": "DIM8"},
            {"name": "DIM9", "type": "float", "title": "DIM9"},
            {"name": "DIM10", "type": "float", "title": "DIM10"},
        ]
        layout = QVBoxLayout()
        self.contentLayout = QHBoxLayout()
        layout.addLayout(self.contentLayout)
        self.leftGridWidget = QWidget()
        self.LeftGridLayout = QGridLayout()
        # self.LeftGridLayout.setVerticalSpacing(5)
        leftLayout = QVBoxLayout()
        self.contentLayout.addLayout(leftLayout)
        self.leftGridWidget.setLayout(self.LeftGridLayout)
        leftLayout.addWidget(self.leftGridWidget)
        self.createParameterUI(self.paramsList, self.LeftGridLayout)
        self.hideALLWidget()

        self.contentLayout.addSpacerItem(
            QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)
        )

        rightLayout = QVBoxLayout()
        self.rightGridWidget = QWidget()
        self.rightGridLayout = QGridLayout()
        # self.rightGridLayout.setVerticalSpacing(5)
        self.rightGridWidget.setLayout(self.rightGridLayout)
        self.createParameterBox1UI(self.paramsList[6:], self.rightGridLayout)
        self.rightGridWidget.setVisible(False)
        rightLayout.addWidget(self.rightGridWidget)

        self.rightImage = QLabel()
        self.rightImage.setAlignment(Qt.AlignCenter)
        self.rightImage.setFixedWidth(200)
        pixmap = QPixmap("icons/plugins/qmodeling/stringed_bar/BAR.png")
        scaled_pixmap = pixmap.scaledToWidth(200, Qt.SmoothTransformation)
        self.rightImage.setPixmap(scaled_pixmap)
        rightLayout.addWidget(self.rightImage)
        self.contentLayout.addLayout(rightLayout)

        self.bottomImage = QLabel()
        self.bottomImage.setVisible(False)
        self.bottomImage.setAlignment(Qt.AlignCenter)
        self.bottomImage.setFixedWidth(360)
        pixmap2 = QPixmap("icons/plugins/qmodeling/stringed_bar/DBOX.png")
        scaled_pixmap2 = pixmap2.scaledToWidth(360, Qt.SmoothTransformation)
        self.bottomImage.setPixmap(scaled_pixmap2)

        bottomImageLayout = QHBoxLayout()
        bottomImageLayout.setAlignment(Qt.AlignCenter)
        bottomImageLayout.addWidget(self.bottomImage)
        layout.addLayout(bottomImageLayout)

        btnLayout = QHBoxLayout()
        btnLayout.setContentsMargins(-1, 10, -1, -1)
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        self.widgetDict["type"].setValue("BAR")

        # if self.type == "edit":
        #     self.updateUI(data=self.data)

        # if self.isPriorityDim:
        #     self.widgetDict["DIM1"].setFocus()

    def updateUI(self, data, isPriorityDim=False):
        self.data = data
        if data:
            self.typeChange(value=data[1])
            self.widgetDict["name"].setValue(data[0])
            self.widgetDict["type"].setValue(data[1])
            sizeList = data[2] or []
            for i, value in enumerate(sizeList):
                self.widgetDict[f"DIM{i+1}"].setValue(value)

            if data[1] == "DBOX":
                for i, value in enumerate(sizeList):
                    if i >= 4:
                        self.widgetDict[f"DIM{i+1}DBOX"].setValue(value)

        if isPriorityDim:
            self.widgetDict["DIM1"].setFocus()

    def on_okBtn_clicked(self):
        dict = {}
        sizeList = []
        name = self.widgetDict["name"].getValue()
        if name in self.names:
            MBox.warning("名称已存在！")
            return
        for key, widget in self.widgetDict.items():
            if widget.isVisible():
                value = widget.getValue()
                if value is None:
                    MBox.warning("请填写完整信息！")
                    return
                if "DIM" in key:
                    sizeList.append(value)
                else:
                    dict[key] = value
        size = ",".join(str(item) for item in sizeList)
        self.close()
        self.ok_signal.emit(
            self.type, [dict.get("name"), dict.get("type"), size], self.row
        )
        

    def typeChange(self, value, *args, **kwargs):

        if value == self.currentType:
            return

        if value != "DBOX":
            self.rightImage.setVisible(True)
            self.rightGridWidget.setVisible(False)
            self.bottomImage.setVisible(False)

        self.hideALLWidget()
        if value == "ROD":
            self.showWidget(2)
        elif value == "BAR" or value == "TUBE" or value == "TUBE2":
            self.showWidget(4)
        elif value == "HEXA":
            self.showWidget(6)
        elif (
            value == "BOX"
            or value == "CHAN"
            or value == "CHAN1"
            or value == "CHAN2"
            or value == "CROSS"
            or value == "H"
            or value == "HAT"
            or value == "l1"
            or value == "T"
            or value == "T1"
            or value == "T2"
            or value == "Z"
        ):
            self.showWidget(8)
        elif value == "BOX1" or value == "I":
            self.showWidget(12)
            if self.currentType == "DBOX":
                self.widgetDict["DIM5"].setValue(self.widgetDict["DIM5DBOX"].getValue())
                self.widgetDict["DIM6"].setValue(self.widgetDict["DIM6DBOX"].getValue())
        elif value == "HAT1":
            self.showWidget(10)
        elif value == "DBOX":
            self.showWidget(8)
            self.rightGridWidget.setVisible(True)
            self.rightImage.setVisible(False)
            self.bottomImage.setVisible(True)

        if self.rightImage.isVisible():
            pixmap = QPixmap(f"icons/plugins/qmodeling/stringed_bar/{value}.png")
            scaled_pixmap = pixmap.scaledToWidth(200, Qt.SmoothTransformation)
            self.rightImage.setPixmap(scaled_pixmap)

        self.currentType = value

        self.adjustSize()

    def hideALLWidget(self):
        for i in range(20):
            self.LeftGridLayout.itemAt(i + 4).widget().hide()

    def showWidget(self, num):
        for i in range(num):
            self.LeftGridLayout.itemAt(i + 4).widget().show()

    def createParameterUI(self, list, layout, row=0, col=0):
        for index, item in enumerate(list):
            name = item.get("name")
            index = row + index
            label = QLabel(item["title"])
            layout.addWidget(label, index, 0 + col)
            if item["type"] == "str":
                self.widgetDict[name] = LineEditStr()
            elif item["type"] == "float":
                self.widgetDict[name] = LineEditFloat()
            elif item["type"] == "select":
                self.widgetDict[name] = SelectBox(
                    options=item["options"], onChanged=item.get("onChanged")
                )

            layout.addWidget(self.widgetDict[name], index, 1 + col)

    def createParameterBox1UI(self, list, layout, row=0, col=0):
        for index, item in enumerate(list):
            name = item.get("name") + "DBOX"
            index = row + index
            label = QLabel(item["title"])
            layout.addWidget(label, index, 0 + col)
            if item["type"] == "str":
                self.widgetDict[name] = LineEditStr()
            elif item["type"] == "float":
                self.widgetDict[name] = LineEditFloat()
            elif item["type"] == "select":
                self.widgetDict[name] = SelectBox(
                    options=item["options"], onChanged=item.get("onChanged")
                )
            # if name == "DIM1" and self.isPriorityDim:
            #     self.widgetDict[name].setFocus()
            layout.addWidget(self.widgetDict[name], index, 1 + col)

    # def gridLayoutRemoveWidget(self, layout, start, total=12):
    #     for row in range(start, total):
    #         for column in range(layout.columnCount()):
    #             # 获取指定位置的控件
    #             item = layout.itemAtPosition(row, column)
    #             if item:
    #                 # 移除控件
    #                 widget = item.widget()
    #                 if widget:
    #                     widget.setParent(None)  # 将控件的父级设置为 None，从而移除它

    # for i in range(layout.rowCount()):
    #     layout.setRowStretch(i, 1)
